package com.example.administrator.ygddriver.weixinnum;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.administrator.ygddriver.R;
import com.example.administrator.ygddriver.base.BaseActivity;
import com.example.administrator.ygddriver.base.BaseHint;
import com.example.administrator.ygddriver.base.LogInformationBean;
import com.example.administrator.ygddriver.base.UserBean;
import com.example.administrator.ygddriver.liteorm.LiteOrmTools;
import com.example.administrator.ygddriver.liteorm.SingleLiteOrm;
import com.example.administrator.ygddriver.tool.CustomPopWindow;
import com.example.administrator.ygddriver.tool.OkGoRequests;
import com.example.administrator.ygddriver.tool.SimpleToolbar;
import com.example.administrator.ygddriver.tool.UrlValuse;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;

/**
 * 佣金提现
 */
public class WeiXinNumActivity extends BaseActivity implements View.OnClickListener {
    private SimpleToolbar simpleToolbar;
    private RelativeLayout bindingRl;
    private String id, token;
    private ImageView mHeadIv;
    private TextView mNameTv, mNextTv, mAllMoneyTv, mSetAllmoneyTv, mWellMoneyTv, mLjTv, mTagTv;
    //判断微信是否绑定成功
    private String tag = "0";
    private EditText mMoneyEt;
    private String c_wxid, current_balance, Current_balance;
    private CustomPopWindow mCustomPopWindow;

    @Override
    public int initLayout() {
        return R.layout.activity_wei_xin_num;
    }

    @Override
    public void initView() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(UrlValuse.WX_BD_ZT);
        registerReceiver(wxBdBroadcastReceiver, myIntentFilter);

        simpleToolbar = findViewById(R.id.activity_wei_xin_num_stb);
        bindingRl = findViewById(R.id.activity_wei_xin_num_rl);
        mHeadIv = findViewById(R.id.activity_wei_xin_num_iv);
        mNameTv = findViewById(R.id.activity_wei_xin_num_name_tv);
        mNextTv = findViewById(R.id.activity_wei_xin_next_tv);
        mMoneyEt = findViewById(R.id.activity_wei_xin_money_et);
        mTagTv = findViewById(R.id.activity_wei_xin_num_tv);
        mAllMoneyTv = findViewById(R.id.activity_wei_xin_all_money_tv);
        mSetAllmoneyTv = findViewById(R.id.activity_wei_xin_set_all_money_tv);
        mWellMoneyTv = findViewById(R.id.activity_wei_xin_well_money_tv);
        mLjTv = findViewById(R.id.activity_wei_xin_lj_money_tv);
        mSetAllmoneyTv.setOnClickListener(this);
        mNextTv.setOnClickListener(this);
        bindingRl.setOnClickListener(this);
    }

    @Override
    public void initDate() {
        LiteOrmTools.getInformation(UserBean.class, this, new LiteOrmTools.On<UserBean>() {
            @Override
            public void hasData(UserBean data) {
                token = data.getC_token();
                id = data.getC_id();
            }
        }, new LiteOrmTools.OFF() {
            @Override
            public void noData() {

            }
        });
        setSimpleToolbar();
        initWxUserInfoHtml(id, token);
    }

    private void setSimpleToolbar() {
        simpleToolbar.setMainTitle("佣金提现");
        simpleToolbar.setMainTitleColor("#000000");
        simpleToolbar.setBackIv(R.mipmap.u126);
        simpleToolbar.setToolColor("#ffffff");
        simpleToolbar.setBackIvClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_wei_xin_num_rl:
                if (tag.equals("0")) {
                    bindingWx();
                } else {
                    setPopW(v);
                }

                break;
            case R.id.activity_wei_xin_next_tv:
                if (tag.equals("0")) {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(WeiXinNumActivity.this, "提示", "请先绑定微信");
                    baseHint.show();
                } else {
                    if (TextUtils.isEmpty(mMoneyEt.getText().toString())) {

                    } else {
                        if (Float.valueOf(mMoneyEt.getText().toString()) <= Float.valueOf(Current_balance)) {
                            if (Float.valueOf(mMoneyEt.getText().toString()) >= 10.0) {
                                initBranchesWithdrawalHtml(id, mMoneyEt.getText().toString(), c_wxid, token);
                            } else {
                                BaseHint baseHint = new BaseHint.addHint().setParameter(WeiXinNumActivity.this, "提示", "提现金额必须大于二十元");
                                baseHint.show();
                            }
                        } else {
                            BaseHint baseHint = new BaseHint.addHint().setParameter(WeiXinNumActivity.this, "提示", "提现不可大于当前余额");
                            baseHint.show();
                        }


                    }

                }

                break;
            case R.id.activity_wei_xin_set_all_money_tv:
                mMoneyEt.setText(current_balance);
                break;
        }
    }

    private void bindingWx() {
        IWXAPI iwxapi;
        iwxapi = WXAPIFactory.createWXAPI(this, null); //初始化微信api
        iwxapi.registerApp(UrlValuse.WXAPP_ID); //注册appid  appid可以在开发平台获取
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        iwxapi.sendReq(req);

    }

    private BroadcastReceiver wxBdBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            intent.getStringExtra("access_token");
            intent.getStringExtra("openid");
            initUserBindHtml(id, intent.getStringExtra("openid"), intent.getStringExtra("access_token"), token);

        }
    };

    //微信绑定
    private void initUserBindHtml(String c_id, String openid, String access_token, String c_token) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_id", c_id);
        hashMap.put("openid", openid);
        hashMap.put("access_token", access_token);
        hashMap.put("c_token", c_token);
        hashMap.put("c_type", UrlValuse.TYPE);
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_WX_BINDING + UrlValuse.USER_BIND, hashMap, UserBindRequestBean.class, new OkGoRequests.OnTrue<UserBindRequestBean>() {
            @Override
            public void hasData(UserBindRequestBean date) {
                if (date.isSuccess()) {
                    initWxUserInfoHtml(id, token);
                } else {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(WeiXinNumActivity.this, "提示", date.getLocalizedMessage());
                    baseHint.show();
                }
            }
        }, new OkGoRequests.OnError<UserBindRequestBean>() {
            @Override
            public void noData() {

            }
        });
    }

    //	司机端我的钱包
    private void initWxUserInfoHtml(String c_id, String c_token) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_driver", c_id);
        hashMap.put("c_token", c_token);
        hashMap.put("c_type", UrlValuse.TYPE);
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_DRIVER + UrlValuse.DRIVER_MY_WALLET, hashMap, WithdrawalToWxRequestBean.class, new OkGoRequests.OnTrue<WithdrawalToWxRequestBean>() {
            @Override
            public void hasData(WithdrawalToWxRequestBean date) {
                if (date.isSuccess()) {
                    if (date.getResult().getC_status().equals("IS_BINDING")) {
                        c_wxid = date.getResult().getC_wxid();
                        Current_balance = date.getResult().getCurrent_balance();
                        mAllMoneyTv.setText("当前余额：" + date.getResult().getCurrent_balance() + "元");
                        mWellMoneyTv.setText("即将到账：" + date.getResult().getAbout_arrive() + "元");
                        mLjTv.setText("累计提现：" + date.getResult().getCumulative_reflect() + "元");
                        current_balance = date.getResult().getCurrent_balance();
                        RequestOptions requestOptions = new RequestOptions()
                                .placeholder(R.mipmap.wx_head)
                                .error(R.mipmap.wx_head)
                                .fallback(R.mipmap.wx_head);
                        Glide.with(WeiXinNumActivity.this).load(date.getResult().getC_headimgurl()).apply(requestOptions).into(mHeadIv);
                        mNameTv.setText(date.getResult().getC_nickname());
                        tag = "1";
                    } else {
                        tag = "0";
                    }
                    mTagTv.setVisibility(View.INVISIBLE);
                } else {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(WeiXinNumActivity.this, "提示", date.getLocalizedMessage());
                    baseHint.show();

                }
            }
        }, new OkGoRequests.OnError<WithdrawalToWxRequestBean>() {
            @Override
            public void noData() {

            }
        });
    }

    //司机微信提现
    private void initBranchesWithdrawalHtml(String c_account, String c_amount, String c_wechat, String c_token) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_account", c_account);
        hashMap.put("c_amount", c_amount);
        hashMap.put("c_wechat", c_wechat);
        hashMap.put("c_token", c_token);
        hashMap.put("c_type", UrlValuse.TYPE);
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_DRIVER + UrlValuse.DRIVER_WITH_DRAWAL, hashMap, BranchesWithdrawalRequextBean.class, new OkGoRequests.OnTrue<BranchesWithdrawalRequextBean>() {
            @Override
            public void hasData(BranchesWithdrawalRequextBean date) {
                if (date.isSuccess()) {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(WeiXinNumActivity.this, "提示", "提现提交成功");
                    baseHint.show();
                } else {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(WeiXinNumActivity.this, "提示", date.getLocalizedMessage());
                    baseHint.show();
                }
            }
        }, new OkGoRequests.OnError<BranchesWithdrawalRequextBean>() {
            @Override
            public void noData() {

            }
        });
    }

    private void setPopW(View v) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_fragment_my_popw, null);
        handleLogic(view);
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(this).setView(view)
                .size(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .enableOutsideTouchableDissmiss(false)// 设置点击PopupWindow之外的地方，popWindow不关闭，如果不设置这个属性或者为true，则关闭
                .setAnimationStyle(R.style.CustomPopWindowStyle) // 添加自定义显示和消失动画
                .create()
                .showAtLocation(v, Gravity.CENTER, 0, 0);
    }

    private void handleLogic(View contentView) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.item_fragment_my_popw_on_tv:
                        initWxUnBundlingHtml(id, c_wxid, token);
                        break;
                    case R.id.item_fragment_my_popw_off_tv:
                        mCustomPopWindow.dissmiss();
                        break;
                }
            }
        };
        TextView onTv = contentView.findViewById(R.id.item_fragment_my_popw_on_tv);
        TextView offTv = contentView.findViewById(R.id.item_fragment_my_popw_off_tv);
        offTv.setOnClickListener(listener);
        onTv.setOnClickListener(listener);
    }

    //微信解绑
    private void initWxUnBundlingHtml(String c_id, String c_wxid, String c_token) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_id", c_id);
        hashMap.put("c_wxid", c_wxid);
        hashMap.put("c_token", c_token);
        hashMap.put("c_type", UrlValuse.TYPE);
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_WX_BINDING + UrlValuse.WX_UNBUNDLING, hashMap, WxJbBean.class, new OkGoRequests.OnTrue<WxJbBean>() {
            @Override
            public void hasData(final WxJbBean date) {
                if (date.isSuccess()) {
                    mCustomPopWindow.dissmiss();
                    mNameTv.setText("");
                    tag = "0";
                    mHeadIv.setImageResource(R.mipmap.wx_head);
                    mTagTv.setVisibility(View.VISIBLE);
                } else {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(WeiXinNumActivity.this, "提示", date.getLocalizedMessage());
                    baseHint.show();
                }
            }
        }, new OkGoRequests.OnError<WxJbBean>() {
            @Override
            public void noData() {

            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (wxBdBroadcastReceiver != null) {
            unregisterReceiver(wxBdBroadcastReceiver);
        }
    }
}
